package com.farmUni.controller;


import com.farmUni.common.BaseContext;
import com.farmUni.common.R;
import com.farmUni.entity.User;
import com.farmUni.entity.Vo.LoginResponseVO;
import com.farmUni.entity.Vo.UserShowVO;
import com.farmUni.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author farm
 * @since 2024-02-07
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R<LoginResponseVO> userLogin(@RequestBody User user){
        String token = userService.userLogin(user);
        LoginResponseVO loginResponseVO = new LoginResponseVO();
        loginResponseVO.setToken(token);
        loginResponseVO.setMsg("登录成功");
        return R.success(loginResponseVO);
    }

    @PostMapping("/login2")
    public R<LoginResponseVO> userLogin2(@RequestBody User user){
        log.info("2222");
        String token = userService.userLogin2(user);
        LoginResponseVO loginResponseVO = new LoginResponseVO();
        if(token == null){
            return R.error("登录失败,无该用户请注册");
        }
        loginResponseVO.setToken(token);
        loginResponseVO.setMsg("登录成功");
        return R.success(loginResponseVO);
    }

    @GetMapping("/getDetail")
    public R<User> getDetail(){
        User user = userService.getDetail();
        return R.success(user);
    }

    @GetMapping("/getDetail2")
    public R<UserShowVO> getDetail2(){
        UserShowVO user = userService.getDetail2();
        return user!= null?R.success(user):R.error("失败");
    }

    @PostMapping("/update")
    public R<User> update(@RequestBody User user){
        user.setOpenid(BaseContext.getCurrentOpenId());
        boolean isSuccess = userService.updateById(user);
        User newUser = userService.getById(BaseContext.getCurrentOpenId());
        return isSuccess?R.success(newUser):R.error("修改失败");
    }

}

